import { Button, Modal, Popconfirm, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import React, { useEffect, useRef, useState } from 'react';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { allMap, panoramaCreate, panoramaList, panoramaUpdate } from '../service';
import type { PanoramaItem, PanoramaPagination } from '../panorama/data';
import { commonStatus } from '@/constant/constant';
import ProForm, {
  ProFormText,
  ProFormSelect,
  ModalForm,
  ProFormDependency,
} from '@ant-design/pro-form';
import ImgUpload from '@/components/ossUpload';
import InfoSpotList from './infospot';
import { generateRandomString } from '@/utils';
import type { MapItem } from '../list/data';
import QRCodeDown from '@/components/QrcodeDown';
import Panolens from '@/components/Panolens';
import IconRadio from './iconRadio';
import { PAGE } from '@/components/QrcodeDown/const';

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: PanoramaItem) => {
  const hide = message.loading('正在添加');

  try {
    await panoramaCreate({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: any, currentRow?: PanoramaItem) => {
  const hide = message.loading('正在修改');

  try {
    await panoramaUpdate({
      guid: currentRow?.guid,
      ...fields,
    });
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败');
    return false;
  }
};

const PanoramaList: React.FC<{ map?: string }> = ({ map }) => {
  const actionRef = useRef<ActionType>();
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  // 位置
  const [infoSpotModalVisible, handleInfoSpotModalVisible] = useState<boolean>(false);

  const [currentRow, setCurrentRow] = useState<PanoramaItem>();

  const [mapData, setMapData] = useState<MapItem[]>([]);

  // 修改表格Ref
  const formRef = useRef<any>();
  // 添加表格Ref
  const formAddRef = useRef<any>();

  async function getAllMapData() {
    const data: MapItem[] = await allMap({});

    setMapData(data);
  }

  useEffect(() => {
    getAllMapData();
  }, []);

  function updateStatus(guid: string, status: number) {
    panoramaUpdate({
      guid,
      status,
    }).then(() => {
      message.success('更改成功');
      actionRef?.current?.reload();
    });
  }

  const columns: ProColumns<PanoramaItem>[] = [
    {
      title: '场景编号',
      dataIndex: 'guid',
      ellipsis: true,
      copyable: true,
    },
    {
      title: '场景名称',
      dataIndex: 'name',
    },
    {
      title: '所属地图',
      dataIndex: 'map_id',
      fieldProps: {
        fieldNames: { label: 'name', value: 'guid' },
        options: mapData,
      },
      valueType: 'select',
    },
    // {
    //   title: '全景图',
    //   dataIndex: 'url',
    //   search: false,
    //   render: (_: any, record: any) => [
    //     <img key='avatar' style={{ width: '80px', height: '80px' }} src={record.url} alt="全景图" />
    //   ]
    // },

    {
      title: '二维码标识',
      dataIndex: 'code_id',
      render: (_: any, record: any) =>
        record.code_id
          ? [
              <QRCodeDown
                key={record.guid}
                width={450}
                imageSettings={{
                  src: 'https://jd-kxwh.oss-cn-beijing.aliyuncs.com/default/2023-12-01/faa725562859428f9a8dd43c68b5bd41logo.png',
                  width: 150,
                  height: 150,
                  excavate: true,
                }}
                value={`${PAGE.SIGNPOST}?id=${record.code_id}`}
                linkText={record.code_id}
                codeName={record?.name}
              />,
            ]
          : '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: commonStatus,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="update"
          // @ts-ignore
          // disabled={record.status != 2}
          onClick={() => {
            // if (record.status != 2) {
            //   return
            // }
            setCurrentRow(record);
            handleUpdateModalVisible(true);
          }}
        >
          {' '}
          编辑{' '}
        </a>,
        record.status != 1 ? (
          <Popconfirm
            key="confirm"
            title="是否确认启动该项目?"
            onConfirm={() => {
              updateStatus(record.guid, 1);
            }}
            okText="是"
            cancelText="否"
          >
            <a type="link">启动</a>
          </Popconfirm>
        ) : (
          <Popconfirm
            key="close"
            title="是否确认关闭该项目?"
            onConfirm={() => {
              updateStatus(record.guid, 2);
            }}
            okText="是"
            cancelText="否"
          >
            <a type="link">关闭</a>
          </Popconfirm>
        ),
        record.status == 1 ? (
          <a
            key="preview"
            href={`/mall/panorama?guid=${record.guid}`}
            target="_blank"
            onClick={() => {
              if (!record.guid) {
                return;
              }
            }}
            rel="noreferrer"
          >
            {' '}
            预览场景{' '}
          </a>
        ) : (
          ''
        ),
        <a
          key="infoSpots"
          onClick={() => {
            setCurrentRow(record);
            handleInfoSpotModalVisible(true);
          }}
        >
          {' '}
          信息点管理{' '}
        </a>,
      ],
    },
  ];
  // 修改或添加表单 name role avatar
  const EditBox = (ref: any) => (
    <>
      <ProFormText
        rules={[
          {
            required: true,
          },
        ]}
        width="md"
        name="name"
        label="场景名称"
      />
      <ProFormSelect
        name="map_id"
        label="所属地图"
        showSearch
        width="md"
        debounceTime={300}
        request={async ({ keyWords }) => {
          try {
            const data = await allMap({ name: keyWords, status: 1 });
            return data.map((item: { guid: string; name: string }) => {
              return {
                value: item.guid,
                label: item.name,
              };
            });
          } catch (error) {
            return [];
          }
        }}
        placeholder="请选择所属地图,输入可搜索"
        rules={[{ required: true, message: '请选择所属地图' }]}
      />
      <ProFormText
        rules={[
          {
            required: true,
            max: 6,
            min: 6,
          },
        ]}
        width="md"
        name="code_id"
        label="二维码标识"
        addonAfter={
          <a
            onClick={() =>
              ref?.current?.setFieldsValue({
                code_id: generateRandomString(),
              })
            }
          >
            随机生成
          </a>
        }
      />

      <ProForm.Item
        name="url"
        label="全景图"
        rules={[
          {
            required: true,
            message: '全景图',
          },
        ]}
      >
        <ImgUpload needCompress={false} limitSize={0} resizeProps={{ quality: 1 }} />
      </ProForm.Item>
      <IconRadio label="场景图标" name="icon" form={ref} />
      <ProFormDependency name={['url']}>
        {({ url }) => {
          if (url) {
            return (
              <div>
                <ProForm.Item name="coordinates" label="相机初始视角">
                  <Panolens type={2} url={url} infoSpot={[]} container={'container'} />
                </ProForm.Item>
              </div>
            );
          }

          return null;
        }}
      </ProFormDependency>
    </>
  );

  return (
    <>
      <ProTable<PanoramaItem, PanoramaPagination>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="guid"
        search={{
          labelWidth: 120,
        }}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
        }}
        toolBarRender={() => [
          <Button
            key="detail"
            type="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            {' '}
            <PlusOutlined /> 创建{' '}
          </Button>,
        ]}
        request={async (params, sort, filter) => {
          return panoramaList(Object.assign({ map_id: map }, params));
        }}
        columns={columns}
      />
      {/* 新建modal */}
      <ModalForm
        title="新建"
        width="600px"
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        modalProps={{
          destroyOnClose: true,
        }}
        formRef={formAddRef}
        initialValues={{ map_id: map }}
        onFinish={async (value) => {
          const success = await handleAdd({ ...value } as PanoramaItem);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        {/* 与编辑组件重复抽离 */}
        {EditBox(formAddRef)}
      </ModalForm>
      {/* 编辑 */}
      <ModalForm
        title="编辑"
        width="600px"
        visible={updateModalVisible}
        onVisibleChange={handleUpdateModalVisible}
        modalProps={{
          destroyOnClose: true,
        }}
        initialValues={{
          ...currentRow,
        }}
        formRef={formRef}
        onFinish={async (value) => {
          const success = await handleUpdate(value, currentRow);
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        {EditBox(formRef)}
      </ModalForm>

      <Modal
        open={infoSpotModalVisible}
        footer={null}
        width={1000}
        onCancel={() => handleInfoSpotModalVisible(false)}
        destroyOnClose
      >
        <InfoSpotList panorama={currentRow?.guid} />
      </Modal>
    </>
  );
};

export default PanoramaList;
